<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'

defineOptions({
  name: 'TodoList',
})

definePage({
  type: 'home',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '待办事项',
  },
})

// 定义待办事项类型
interface TodoItem {
  id: string
  content: string
  completed: boolean
  createTime: number
}

// 待办事项列表
const todoList = reactive<TodoItem[]>([])
// 新待办事项输入框内容
const newTodo = ref('')
// 输入框焦点状态
const inputFocused = ref(false)

// 从本地存储加载待办事项
function loadTodos() {
  const savedTodos = uni.getStorageSync('todoList')
  if (savedTodos) {
    try {
      const parsedTodos = JSON.parse(savedTodos) as TodoItem[]
      todoList.splice(0, todoList.length, ...parsedTodos)
    }
    catch (error) {
      console.error('加载待办事项失败:', error)
    }
  }
}

// 保存待办事项到本地存储
function saveTodos() {
  uni.setStorageSync('todoList', JSON.stringify(todoList))
}

// 添加新待办事项
function addTodo() {
  const content = newTodo.value.trim()
  if (!content) {
    uni.showToast({ title: '请输入待办事项内容', icon: 'none' })
    return
  }

  const newItem: TodoItem = {
    id: Date.now().toString(),
    content,
    completed: false,
    createTime: Date.now(),
  }

  todoList.unshift(newItem)
  newTodo.value = ''
  saveTodos()
}

// 切换待办事项完成状态
function toggleTodo(id: string) {
  const todo = todoList.find(item => item.id === id)
  if (todo) {
    todo.completed = !todo.completed
    saveTodos()
  }
}

// 删除待办事项
function deleteTodo(id: string) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个待办事项吗？',
    success: (res) => {
      if (res.confirm) {
        const index = todoList.findIndex(item => item.id === id)
        if (index !== -1) {
          todoList.splice(index, 1)
          saveTodos()
        }
      }
    },
  })
}

// 清空所有待办事项
function clearAllTodos() {
  if (todoList.length === 0) {
    uni.showToast({ title: '没有待办事项可清空', icon: 'none' })
    return
  }

  uni.showModal({
    title: '确认清空',
    content: '确定要清空所有待办事项吗？',
    success: (res) => {
      if (res.confirm) {
        todoList.length = 0
        saveTodos()
      }
    },
  })
}

// 获取当前日期
function getCurrentDate() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekday = weekdays[date.getDay()]
  return `${year}年${month}月${day}日 ${weekday}`
}

// 页面加载时加载待办事项
onMounted(() => {
  loadTodos()
})
</script>

<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 自定义导航栏 -->
    <view class="sticky top-0 z-10 bg-white shadow-sm">
      <view class="h-14 flex items-center justify-between px-4">
        <view class="text-lg text-gray-800 font-medium">
          待办事项
        </view>
        <view class="text-sm text-gray-500">
          {{ getCurrentDate() }}
        </view>
      </view>
    </view>

    <!-- 待办事项内容区 -->
    <view class="p-4">
      <!-- 添加待办事项输入框 -->
      <view class="mb-6 flex gap-2">
        <input
          v-model="newTodo"
          type="text"
          placeholder="请输入待办事项..."
          :focus="inputFocused"
          class="flex-1 border border-gray-300 rounded-lg px-4 py-3 text-base transition-all focus:border-blue-500 focus:outline-none"
          @focus="inputFocused = true"
          @blur="inputFocused = false"
          @confirm="addTodo"
        >
        <button
          class="flex-shrink-0 rounded-lg bg-blue-500 px-4 py-3 text-sm text-white font-medium transition-all active:bg-blue-700 hover:bg-blue-600"
          @click="addTodo"
        >
          添加
        </button>
      </view>

      <!-- 待办事项列表 -->
      <view v-if="todoList.length > 0" class="mb-6 space-y-3">
        <view
          v-for="todo in todoList"
          :key="todo.id"
          class="rounded-lg bg-white p-4 shadow-sm transition-all hover:shadow-md"
        >
          <view class="flex items-start justify-between gap-3">
            <view class="flex-1">
              <view
                class="flex items-start gap-3"
                @click="toggleTodo(todo.id)"
              >
                <!-- 复选框 -->
                <view
                  class="mt-0.5 h-5 w-5 flex items-center justify-center border-2 rounded-full transition-all"
                  :class="todo.completed ? 'border-green-500 bg-green-500' : 'border-gray-300 bg-white hover:border-blue-500'"
                >
                  <text v-if="todo.completed" class="text-xs text-white">✓</text>
                </view>
                <!-- 待办内容 -->
                <view class="flex-1">
                  <view
                    class="text-base leading-tight"
                    :class="todo.completed ? 'text-gray-400 line-through' : 'text-gray-800'"
                  >
                    {{ todo.content }}
                  </view>
                  <view class="mt-1 text-xs text-gray-400">
                    {{ new Date(todo.createTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) }}
                  </view>
                </view>
              </view>
            </view>
            <!-- 删除按钮 -->
            <view
              class="mt-1 h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-gray-100 text-gray-500 transition-all active:bg-red-200 hover:bg-red-100 hover:text-red-500"
              @click="deleteTodo(todo.id)"
            >
              <text class="text-xs">×</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态提示 -->
      <view v-else class="rounded-lg bg-white p-8 text-center shadow-sm">
        <!-- <image src="/static/logo.svg" alt="" class="mx-auto mb-4 h-20 w-20 opacity-30" /> -->
        <view class="text-gray-500">
          暂无待办事项
        </view>
        <view class="mt-2 text-sm text-gray-400">
          添加一些待办事项开始吧！
        </view>
      </view>

      <!-- 清空按钮 -->
      <view v-if="todoList.length > 0" class="flex justify-center">
        <button
          class="border border-gray-300 rounded-full bg-white px-6 py-2 text-sm text-gray-600 transition-all hover:border-gray-400 active:bg-gray-50 hover:text-gray-700"
          @click="clearAllTodos"
        >
          清空所有
        </button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
/* 使用了UNOCSS原子化类名，无需额外样式 */
</style>
